local fs   = require "nixio.fs"
local util = require "nixio.util"
local json = require "luci.jsonc"

require"luci.sys"
if fs.access("/etc/config/nwt") then
	m = Map("nwt", translate("串口"), translate("控制器串口配置"))
	s = m:section(TypedSection, "serial", "")
	s.addremove = false
	s.anonymous = true

	local devices = {}
	util.consume((fs.glob("/dev/ttyU*")), devices)
	util.consume((fs.glob("/dev/ttyA*")), devices)
	port = s:option(ListValue, "serialport", translate("Serial Port"))
	for k, v in ipairs(devices) do
	    if v ~= "lo" then
	        port:value(v)
	    end
	end

	ratelist = {110,300,600,1200,2400,4800,9600,14400,19200,38400,57600,115200,230400}
	rate = s:option(ListValue, "baudrate", translate("Baud Rate"))
	for k, v in ipairs(ratelist ) do
        rate:value(v)
	end
--[[
	function rate.write(self, section, value)
		local serialport = m.uci:get("nwt",section,"serialport")
		local str = string.format("echo '%s %s raw speed %s' >>/var/log/serial.log 2>&1",section,serialport,value)
		os.execute(str)
		m.uci:set("nwt",section,"baudrate",value)
	end
]]
	m.on_after_commit = function()
		local uci = require "luci.model.uci".cursor()
		local serialport = uci:get_first("nwt","serial","serialport")
		local baudrate = uci:get_first("nwt","serial","baudrate")
		local nwtconf = json.parse(fs.readfile("/etc/nwt.json") or "")
		if type(nwtconf) == "table" then
        	nwtconf.serial = {port=serialport,rate=baudrate}
        	local js = json.stringify(nwtconf)
			fs.writefile("/etc/nwt.json",js)
		else
			local nwtconf = {serial={port=serialport,rate=baudrate}}
        	local js = json.stringify(nwtconf)
			fs.writefile("/etc/nwt.json",js)
        end
		--TODO restart serial client
		luci.sys.call("/etc/init.d/nwt restart")
	end
--[[
	local apply = luci.http.formvalue("cbi.apply")
	if apply then
	--    io.popen("/etc/init.d/njitclient restart")
	end
]]
	return m
end
